package com.study.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.exceptions.CourseException;
import com.study.exceptions.CourseSeckillException;
import com.study.seckill.dao.CourseSeckillDao;
import com.study.seckill.dao.CourseSeckillMapper;
import com.study.seckill.entity.CourseSeckill;
import com.study.seckill.service.CourseSeckillService;
import com.study.seckill.service.CourseService;
import com.study.seckill.vo.CourseSeckillDetailVO;
import com.study.util.ResponseResult;
import com.study.vo.CourseInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName: CourseSeckillServiceImpl
 * @Author: wYin
 * @Date: 2022/3/10 14:41
 */
@Service
public class CourseSeckillServiceImpl extends ServiceImpl<CourseSeckillMapper, CourseSeckill> implements CourseSeckillService {

    @Autowired
    private CourseSeckillDao courseSeckillDao;

    @Autowired
    private CourseSeckillMapper courseSeckillMapper;

    @Autowired
    private CourseService courseService;

    @Override
    public List<CourseSeckill> showCourseSeckill() {
        return courseSeckillMapper.getShowCourseSeckill();
    }

    @Override
    public String add(CourseSeckill courseSeckill) {

        CourseSeckill save = courseSeckillDao.save(courseSeckill);
        return null;
    }

    /**
     * @Desc: 根据传入的秒杀id和秒杀数量更新秒杀的库存
     * @Param: [courseSeckill]
     * @Return: boolean
     * @Author: wYin
     * @Time: 2022/3/14 10:03
     */
    @Override
    @Transactional
    public boolean updateSeckillStock(CourseSeckill courseSeckill){
        //根据秒杀的id查询
        CourseSeckill courseSeckill1 = courseSeckillMapper.selectById(courseSeckill.getId());
        if(courseSeckill1==null){
            throw new CourseException("没有查询到当前描述课程");
        }
        //更新订单
        boolean result = courseSeckillMapper.updateSeckillStock(courseSeckill.getId(),courseSeckill1.getVersion());
        if(!result){
            throw new CourseException("更新失败");
        }
        return  true;
    }

    @Override
    public CourseSeckillDetailVO getSeckillInfoById(Integer id) {
        //根据id查询秒杀信息
        CourseSeckill courseSeckill = courseSeckillMapper.selectById(id);
        if(courseSeckill==null){
            throw new CourseSeckillException("未查询到当前秒杀的信息");
        }
        //根据秒杀的信息查询课程的信息
        ResponseResult<CourseInfoVO> courseInfoVO = courseService.getById(courseSeckill.getCourseId());
        if(courseInfoVO.getCode()!=200){
            throw new CourseException("未查询到该商品信息");
        }
        CourseSeckillDetailVO courseSeckillDetailVO = new CourseSeckillDetailVO();
        courseSeckillDetailVO.setCourseSeckill(courseSeckill);
        courseSeckillDetailVO.setCourseInfoVO(courseInfoVO.getData());
        return courseSeckillDetailVO;
    }
}
